package com.tim.app.ui.fragment.selceted;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrClassicFrameLayout;
import com.application.library.widget.refresh.PtrDefaultHandler;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ProblemListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.SearchTopicActivity;
import com.tim.app.ui.activity.selected.QuestionAndAnswerDetailActivity;
import com.tim.app.ui.adapter.selceted.QuestionAndAnswerInfoAdapter;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 问题列表
 */
public class QuestionAndAnswerListFragment extends BaseFragment implements PtrHandler, View.OnClickListener, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    private static final String TAG = "QuestionAndAnswerListFragment";
    private View rootView;
    private PtrClassicFrameLayout refresh_layout;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvQuestionAndAnswerResult;
    private EmptyLayout emptyLayout;
    private QuestionAndAnswerInfoAdapter adapter;
    private List<Problem> dataList;
    private int pageNumber = 1;

    private LinearLayout llEmptyContainer;
    private TextView tvAddSubject;
    private TextView goodAtHeaderView;

    int type;

    public static QuestionAndAnswerListFragment newInstance(int type) {
        QuestionAndAnswerListFragment newFragment = new QuestionAndAnswerListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        newFragment.setArguments(bundle);
        return newFragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_question_and_answer, container, false);

            refresh_layout = (PtrClassicFrameLayout) rootView.findViewById(R.id.refresh_layout);
            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvQuestionAndAnswerResult = (WrapRecyclerView) rootView.findViewById(R.id.wrvQuestionAndAnswerResult);

            llEmptyContainer = (LinearLayout) rootView.findViewById(R.id.llEmptyContainer);
            tvAddSubject = (TextView) rootView.findViewById(R.id.tvAddSubject);
            tvAddSubject.setOnClickListener(this);

            wrvQuestionAndAnswerResult.setOverScrollMode(View.OVER_SCROLL_NEVER);

            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            refresh_layout.disableWhenHorizontalMove(true);
            refresh_layout.setPtrHandler(this);

            if (dataList == null) {
                dataList = new ArrayList<>();
            }
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvQuestionAndAnswerResult.setLayoutManager(layoutManager);
            wrvQuestionAndAnswerResult.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.dimen_1)).build());
            Bundle args = getArguments();
            if (args != null) {
                type = args.getInt("type");
            }
            adapter = new QuestionAndAnswerInfoAdapter(getActivity(), dataList, type);
            adapter.setOnItemClickListener(this);
            wrvQuestionAndAnswerResult.setAdapter(adapter);
        } else {
            if (null != refresh_layout) {
                refresh_layout.refreshComplete();
            }
        }
        emptyLayout = new EmptyLayout(getActivity(), refresh_layout);
        if (AppKey.PROBLEM_TYPE_BE_INVIED == type) {
            emptyLayout.setEmptyText("还没有收到任何人的邀请", "");
            emptyLayout.setEmptyButtonShow(false);
            emptyLayout.setEmptyDrawable(R.drawable.ic_empty_follow);
        } else if (AppKey.PROBLEM_TYPE_HOT == type) {
            emptyLayout.setEmptyText("暂无最热问题", "");
            emptyLayout.setEmptyDrawable(R.drawable.ic_empty_problem);
        } else if (AppKey.PROBLEM_TYPE_NEWEST == type) {
            emptyLayout.setEmptyText("暂无最新问题", "");
            emptyLayout.setEmptyDrawable(R.drawable.ic_empty_problem);
        } else if (AppKey.PROBLEM_TYPE_RECOMMAND == type) {
            goodAtHeaderView = new TextView(getContext());
            goodAtHeaderView.setBackgroundColor(getResources().getColor(R.color.view_background_color));
            goodAtHeaderView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, (int) RT.getDensity() * 30));
            goodAtHeaderView.setGravity(Gravity.CENTER);
            goodAtHeaderView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
            goodAtHeaderView.setTextColor(getResources().getColor(R.color.text_desc_color));
            goodAtHeaderView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    EventManager.ins().sendEvent(EventTag.GOTO_SUBJECT, 0, 0, null);
                }
            });
            wrvQuestionAndAnswerResult.addHeaderView(goodAtHeaderView);
        }
        emptyLayout.showLoading();
        emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.showLoading();
                initData();
            }
        });
        initData();
        EventManager.ins().registListener(EventTag.ON_QUESTION_DELETED, eventListener);
        return rootView;
    }

    int goodAtTopicCount = 0;

    public void initData() {
        pageNumber = 1;
        switch (type) {
            case AppKey.PROBLEM_TYPE_RECOMMAND:
                if (UserManager.ins().isLogin()) {
                    API_User.ins().getGoodAtTopicProblem(TAG, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
                } else {
                    showTopicUi();
                }
                break;
            case AppKey.PROBLEM_TYPE_NEWEST:
                API_Found.ins().getNewProblemList(TAG, false, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
                break;
            case AppKey.PROBLEM_TYPE_HOT:
                API_Found.ins().getNewProblemList(TAG, true, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
                break;
            case AppKey.PROBLEM_TYPE_BE_INVIED:
                if (UserManager.ins().isLogin()) {
                    API_User.ins().getInvitedProblemList(TAG, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
                } else {
                    emptyLayout.showEmpty();
                }
                break;
        }
    }

    private void loadMoreData(int type) {
        switch (type) {
            case AppKey.PROBLEM_TYPE_RECOMMAND:
                if (UserManager.ins().isLogin()) {
                    API_User.ins().getGoodAtTopicProblem(TAG, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
                } else {
                    showTopicUi();
                }
                break;
            case AppKey.PROBLEM_TYPE_NEWEST:
                API_Found.ins().getNewProblemList(TAG, false, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
                break;
            case AppKey.PROBLEM_TYPE_HOT:
                API_Found.ins().getNewProblemList(TAG, true, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
                break;
            case AppKey.PROBLEM_TYPE_BE_INVIED:
                if (UserManager.ins().isLogin()) {
                    API_User.ins().getInvitedProblemList(TAG, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
                }
                break;
        }
    }

    private void showTopicUi() {
        if (AppKey.PROBLEM_TYPE_RECOMMAND == type) {
            emptyLayout.showContent();
            if (goodAtTopicCount > 0) {
                refresh_layout.setVisibility(View.VISIBLE);
                llEmptyContainer.setVisibility(View.GONE);
                goodAtHeaderView.setText(getString(R.string.fromGoodAt, String.valueOf(goodAtTopicCount)));
                adapter.notifyDataSetChanged();
            } else {
                refresh_layout.setVisibility(View.GONE);
                llEmptyContainer.setVisibility(View.VISIBLE);
            }
        }
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_QUESTION_DELETED:
                    String deleteId = (String) dataobj;
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i).getId().equals(deleteId)) {
                            dataList.remove(i);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onAttachFragment(Fragment childFragment) {
        super.onAttachFragment(childFragment);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.ON_QUESTION_DELETED, eventListener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvAddSubject:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getActivity());
                    return;
                }
                SearchTopicActivity.start(getContext());
                break;
        }
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (null != dataList && dataList.size() > position) {
            Problem problem = dataList.get(position);
            QuestionAndAnswerDetailActivity.start(getContext(), problem, false);
        }
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        loadMoreData(type);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errmsg, int id, boolean fromcache) {
            refresh_layout.refreshComplete();
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                ProblemListResult infoResult = new Gson().fromJson(resultValue, ProblemListResult.class);
                if (null != infoResult.getRes() && infoResult.getRes().getArraylist() != null) {
                    if (AppKey.PROBLEM_TYPE_RECOMMAND == type && null != infoResult.getRes().getArraylist().getMap()) {
                        goodAtTopicCount = infoResult.getRes().getArraylist().getMap().getAdeptTopicCount();
                    }
                    if (null != infoResult.getRes().getArraylist().getResult()) {
                        dataList.addAll(infoResult.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNumber = infoResult.getRes().getArraylist().getCurrentPageNo();
                    if (infoResult.getRes().getArraylist().getCurrentPageNo() != infoResult.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(true, false);
                    }
                } else {
                    goodAtTopicCount = 0;
                }
                if (dataList.size() == 0) {
                    if (AppKey.PROBLEM_TYPE_RECOMMAND == type) {
                        if (wrvQuestionAndAnswerResult.getAdapter().getItemCount() == 0) {
                            emptyLayout.showEmpty();
                        } else {
                            load_more.loadMoreFinish(false, false);
                            emptyLayout.showContent();
                        }
                    } else {
                        emptyLayout.showEmpty();
                    }
                } else {
                    emptyLayout.showContent();
                }
                showTopicUi();
            } else {
                showTopicUi();
                if (AppKey.PROBLEM_TYPE_RECOMMAND == type) {
                    if (wrvQuestionAndAnswerResult.getAdapter().getItemCount() == 0) {
                        emptyLayout.showEmpty();
                    } else {
                        emptyLayout.showContent();
                    }
                } else {
                    emptyLayout.showEmptyOrError(errcode);
                }
                ToastUtil.showToast(errmsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errmsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                ProblemListResult infoResult = new Gson().fromJson(resultValue, ProblemListResult.class);
                if (null != infoResult.getRes() && infoResult.getRes().getArraylist() != null) {
                    if (null != infoResult.getRes().getArraylist().getResult()) {
                        dataList.addAll(infoResult.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNumber = infoResult.getRes().getArraylist().getCurrentPageNo();
                    if (infoResult.getRes().getArraylist().getCurrentPageNo() != infoResult.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(true, false);
                    }
                }
            } else {
                ToastUtil.showToast(errmsg);
            }
            return false;
        }
    };

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, wrvQuestionAndAnswerResult, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        initData();
    }
}
